console.log('background is running')

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('background收到消息:', request);

  // 处理消息
  switch (request.type) {
    case 'COUNT':
      console.log('background has received a message from popup, and count is ', request?.count);
      break;

    case 'OPEN_SIDEPANEL':
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]) {
          chrome.sidePanel.open({ tabId: tabs[0].id });
        }
      });
      break;

    case 'OPEN_POPUP':
      chrome.windows.create({
        url: chrome.runtime.getURL('popup.html'),
        type: 'popup',
        width: 400,
        height: 600
      });
      break;

    // 处理来自contentScript的postMessage消息
    case '发布文章':
      console.log('background收到contentScript转发的消息:', request.message);

      const reqMessage = request.message;

      // 处理发布文章动作
      if (reqMessage.action === '发布文章') {

        // 发送响应，返回接收到的完整数据
        sendResponse({
          success: true,
          traceId: reqMessage.traceId,
          message: '插件收到了发布文章请求，正在执行',
          timestamp: Date.now(),
          receivedData: reqMessage.data // 返回接收到的完整数据
        });

        // 打开一个新的标签页，同时打开侧边栏
        chrome.tabs.create({
          url: 'https://mp.weixin.qq.com',
          active: true
        }, (tab) => {
          chrome.sidePanel.open({ tabId: tab.id });
        });

        return true; // 保持消息通道开放
      }
    default:
      console.log('background收到未知消息:', request);
      break;
  }


})


// 监听扩展安装事件
chrome.runtime.onInstalled.addListener(() => {

  // 安装扩展时，设置sidePanel的行为
  chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false });
});
